﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Grpc.Core;
using UserCenter.Grpc;
using UserCenter.Grpc.Client;
using Google.Protobuf;
using UserCenter.Api.Tools;
using UserCenter.BLL;
using UserCenter.Api.Core;

namespace UserCenter.Api.Services
{
    public class MemberApiImpl : MemberApi.MemberApiBase
    {
        const int ECH = 0x7;
        BaseMerchantImpl _baseMerchantImpl = new BaseMerchantImpl();


        /// <summary>
        /// 设置头像
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task<SetAvaterResponse> SetAvater(SetAvaterRequest request, ServerCallContext context)
        {
            string url = Utils.UploadBase64Image(context, request.AvaterData.ToByteArray(), true);
            if (url != null)
            {
                MemberBLL.SetAvater(context.MemberId(), url);
                return Task.FromResult(new SetAvaterResponse { AvaterUrl = url });
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 设置扩展
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task<BoolValue> SetExt(SetExtRequest request, ServerCallContext context)
        {
            return _baseMerchantImpl.SetExt(request, context);
        }

        /// <summary>
        /// 设置父级
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task<BoolValue> SetParent(SetParentRequest request, ServerCallContext context)
        {
            return _baseMerchantImpl.SetParent(request, context);
        }



        /// <summary>
        /// 设置密码
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task<BoolValue> SetPassword(SetPasswordRequest request, ServerCallContext context)
        {
            var memberId = context.MemberId();
            if (request.Type >= byte.MinValue && request.Type <= byte.MaxValue)
            {
                var pwdType = Convert.ToByte(request.Type);
                var password = MemberBLL.Password(memberId, pwdType);
                if (!string.IsNullOrEmpty(request.SmsId))
                {
                    var log = SmsCodeLogBLL.Info(request.SmsId);
                    if (log == null)
                    {
                        context.Throw(ECH, 17);
                        return null;
                    }
                    if (log.IsValidate || log.CreateTime.AddMinutes(5) < DateTime.Now)
                    {
                        context.Throw(ECH, 18);
                        return null;
                    }
                    var saved = false;
                    if (password != null)
                    {
                        saved = MemberBLL.UpdatePassword(memberId, pwdType, request.Password);
                    }
                    else
                    {
                        saved = MemberBLL.CreatePassword(memberId, pwdType, request.Password);
                    }
                    return Task.FromResult(new BoolValue() { Value = saved });
                }
                else
                {
                    if (!password.Password.Equals(request.OldPassword, StringComparison.InvariantCultureIgnoreCase))
                    {
                        context.Throw(ECH, 20);
                        return null;
                    }
                    else
                    {
                        var saved = MemberBLL.UpdatePassword(memberId, pwdType, request.Password);
                        return Task.FromResult(new BoolValue() { Value = saved });
                    }

                }
            }
            else
            {
                context.Throw(ECH, 0x9);
                return null;
            }


        }

        /// <summary>
        /// 获取当前用户资料
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task<GetMemberResponse> GetMember(Empty request, ServerCallContext context)
        {
            return _baseMerchantImpl.GetMember(context.MemberId(), context);
        }

        /// <summary>
        /// 检查密码
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>

        public override Task<BoolValue> CheckPassword(CheckPasswordRequest request, ServerCallContext context)
        {
            if (request.Type >= byte.MinValue && request.Type <= byte.MaxValue)
            {
                var password = MemberBLL.Password(context.MemberId(), Convert.ToByte(request.Type));
                return Task.FromResult(new BoolValue() { Value = password != null });
            }
            else
            {
                context.Throw(ECH, 0x9);
                return null;
            }

        }

        public override Task<GetMemberResponse> GetParentId(Empty request, ServerCallContext context)
        {
            var memberId = MemberBLL.GetParentId(context.MemberId());
            if (memberId < 1)
            {
                context.Throw(ECH, 21);
                return null;
            }
            else
            {
                return _baseMerchantImpl.GetMember(memberId, context);
            }
        }

        public override Task<BoolValue> SetChild(MemberIdRequest request, ServerCallContext context)
        {
            //TODO 检查客户端传入的用户是否是否属于当前商户 
            var parentId = MemberBLL.GetParentId(request.MemberId);
            if (parentId > 0)
            {
                context.Throw(ECH, 22);
                return null;
            }
            return _baseMerchantImpl.SetParent(new Models.SetParentsRequest()
            {
                MemberId = request.MemberId,
                ParentId = context.MemberId(),
            }, context);
        }

        public override Task<BoolValue> BindPhone(BindPhoneRequest request, ServerCallContext context)
        {
            UserCenter.Models.DeviceType? deviceType = null;
            var log = SmsCodeLogBLL.Info(request.SmsId);
            if (log == null)
            {
                context.Throw(ECH, 17);
                return null;
            }
            if (log.IsValidate || log.CreateTime.AddMinutes(5) < DateTime.Now)
            {
                context.Throw(ECH, 18);
                return null;
            }
            if (!Utils.CheckByteEnum(request.DeviceType, out deviceType))
            {
                context.Throw(ECH, 18);
                return null;
            }
            string code = request.Code;
            var accounts = string.IsNullOrEmpty(ApiConfig.Default.TestAccount) ? new string[] { } : ApiConfig.Default.TestAccount.Split(',');
            if (accounts.Contains(log.Phone))
            {
                code = log.Code;
            }
            if (!log.Code.Equals(code, StringComparison.InvariantCultureIgnoreCase))
            {
                context.Throw(ECH, 19);
                return null;
            }
            else
            {
                string ip = context.ClientIp();
                var member = MemberBLL.Info(context.MerchantId(), log.Phone);
                if (member != null)
                {
                    context.Throw(ECH, 29);
                    return null;
                }
                else
                {
                    var r = MemberBLL.UpdateUserName(context.MemberId(), log.Phone);
                    return Task.FromResult(new BoolValue() { Value = r });
                }

            }
        }
    }
}
